<template>
	<view style="width:100%;height:100%;overflow:hidden !important;">
        <!-- <movable-area> -->
            <view style="margin-bottom:60rpx;overflow: hidden;width:100%;float:left;clear:both;">

                <indexcom  ref="index" v-show="PageCur=='index'" @getLoadMoreState="handleLoadMoreState" @getCall="handleGetCall"></indexcom>
            
                <infoself v-show="PageCur=='info'" ref="info_self" @getLoadMoreState="handleLoadMoreState"></infoself>
                
                <orderself v-show="PageCur=='order'" ref="order_self"></orderself>
                
                <websip v-show="PageCur=='websip'" :currentpage="PageCur" ref="websip" ></websip>
                
                <me v-if="PageCur=='me'" ref="me"></me>

            </view>

            <view class="box">
                <view class="cu-bar tabbar bg-white shadow foot">
                    <view class="action" @click="NavChange" data-cur="index">
                        <view class='cuIcon-cu-image'>
                            <view class="cu-tag badge" v-show="callCounts > 0">{{callCounts}}</view>
                            <image v-if="PageCur=='index'" src="../../static/tabBar/index_cur.png"></image>
                            <image v-if="PageCur != 'index'" src="../../static/tabBar/index.png"></image>
                        </view>
                        <view :class="PageCur=='index'?'color_main':'text-gray'">通话</view>
                    </view>

                    <view class="action" @click="NavChange" data-cur="info">
                        <view class='cuIcon-cu-image'>

                            <image v-if="PageCur=='info'" src="../../static/tabBar/shop_cur.png"></image>
                            <image v-if="PageCur != 'info'" src="../../static/tabBar/shop.png"></image>
                        </view>
                        <view :class="PageCur=='info'?'color_main':'text-gray'">任务</view>
                    </view>
                    
                    <view class="action" @click="NavChange" data-cur="order">
                        <view class='cuIcon-cu-image'>
                    
                            <view class="cu-tag badge" v-show="orderCounts > 0">{{orderCounts}}</view>
                            <image v-if="PageCur=='order'" src="../../static/tabBar/order_cur.png"></image>
                            <image v-if="PageCur != 'order'" src="../../static/tabBar/order.png"></image>
                        </view>
                        <view :class="PageCur=='order'?'color_main':'text-gray'">订单</view>
                    </view>
                    
                    <view class="action" @click="NavChange" data-cur="websip">
                        <view class='cuIcon-cu-image'>
                            <image v-if="PageCur=='websip'" src="../../static/tabBar/sip_cur.png"></image>
                            <image v-if="PageCur != 'websip'" src="../../static/tabBar/sip.png"></image>
                        </view>
                        <view :class="PageCur=='websip'?'color_main':'text-gray'">SIP</view>
                    </view>

                    <view class="action" @click="NavChange" data-cur="me">
                        <view class='cuIcon-cu-image'>
                            <image v-if="PageCur=='me'" src="../../static/tabBar/me_cur.png"></image>
                            <image v-if="PageCur != 'me'" src="../../static/tabBar/me.png"></image>
                        </view>
                        <view :class="PageCur=='me'?'color_main':'text-gray'">我的</view>
                    </view>

                </view>
            </view>
            
            <uni-load-more v-if="PageCur == 'index' || PageCur == 'info'" :status="status" :icon-size="16" :content-text="contentText" style="margin-bottom:150rpx;width:100%;float:left;clear:both;" />
            
            <u-modal v-model="isShowOpenVoice" :show-cancel-button="true" :title-style="{fontSize:'40rpx'}" confirm-text="去开启" title="未开启通话自动录音功能" @cancel="isShowOpenVoice = false" @confirm="confirmOpenVoice">
                <view class="slot-content" style="height:400rpx;">
                    <text>请自动开启通话录音功能,否则无法进行外呼并生成通话录音。以下为开启方法:</text>
                    <text>1.在手机自带拨号盘通话设置中,开启'通话自动录音'</text>
                    <text>2.在系统设置中,搜索'自动录音'或'通话设置',开启'通话自动录音'</text>
                </view>
            </u-modal>
            
            <u-modal v-model="isShowOpenFile" :show-cancel-button="true" :title-style="{fontSize:'40rpx'}" confirm-text="去开启" title="未开启“所有文件”访问权限" @cancel="isShowOpenFile = false" @confirm="confirmOpenFile">
                <view class="slot-content">
                    <text>请开启“所有文件”访问权限功能,否则无法获取通话录音文件。</text>
                </view>
            </u-modal>
            
            <movable-area >
                <!-- <movable-view :x="xTask" :y="yTask" direction="all" out-of-bounds v-if="PageCur != 'websip'">
                    <view class="task_panel">
                        <view style="float:left;">任务数量<br>{{time}}</view>
                    </view>
                </movable-view> -->
				
				<movable-view :x="xTask" :y="yTask" direction="all" out-of-bounds v-if="currentCallType == 'sip'"  style="width:390rpx;">
				    <view class="task_panel">
				        <view style="float:left;text-align: left;">SIP呼叫:{{callingTime}}<br><text>{{callingData.phone}}</text> </view>
						<u-button type="error" style="float:right;height:70rpx;width:100rpx;margin-right:25rpx;" :disabled="callStatus == 0" text="挂断通话" @click="handleEndCall()" >挂断</u-button>
				    </view>
				</movable-view>
                
                <movable-view :x="xPhone" :y="yPhone" direction="all" out-of-bounds v-if="PageCur != 'websip'">
                    <view class="number_panel" @click.stop="onHandleOpenCallPhone()">
                         <i class="iconfont" >&#xe954;</i>
                         <view class="txt" >拨号</view>
                     </view>
                </movable-view>
				
				<!-- <movable-view :x="xPhone" :y="yPhone" direction="all" out-of-bounds >
				    <view class="number_panel" @click.stop="handleSqliteList()">
				         <i class="iconfont" >&#xe954;</i>
				         <view class="txt" >测试</view>
				     </view>
				</movable-view>-->
				
				<!-- <movable-view :x="xPhone" :y="yPhone" direction="all" out-of-bounds >
				    <view class="number_panel" @click.stop="handleSqliteUpdate()">
				         <i class="iconfont" >&#xe954;</i>
				         <view class="txt" >修改</view>
				     </view>
				</movable-view> -->
                
                <movable-view :x="xInfo" :y="yInfo" direction="all" out-of-bounds v-if="PageCur != 'websip'">
                    <view v-if="PageCur == 'info'" :class="isCallStatus == '' ? 'call_next':'call_next_nocall'" @click="handleCallNext()" >
                        <view>呼叫<br>下一个</view>
                    </view>
                </movable-view>
				
            </movable-area>

	</view>
</template>

<script>
	import indexcom from "./index.vue"; //首页

	import infoself from "./infoself.vue"; //APP任务应用
	import orderself from "./orderself.vue"; //APP订单应用
    import websip from "./websip.vue"; //WEBSIP应用
    
	import me from "./me.vue"; //个人中心

	import {
		mapGetters,mapState
	} from "vuex"

	import {
		getCallTaskBlack,
        addCallOutDataNoVoice,
		addCallOutDataNoVoicePro
	} from "@/api/index.js";
	
	import {
		getOrderRemindCount,
        changeCallNumStatus
	} from "@/api/task.js";
	
	import UniWorker from '@/uni_modules/xzh-worker/js_sdk/index.js'
	
	import {getHms,convertToUnixWithAddedSeconds,getTime,GetDateDiff} from '@/utils/data.js';
	
	import DB from "@/utils/sqlite.js";
	
	import request from '@/common/request.js';
	
	let that;
	
	const callModule = uni.requireNativePlugin("leven-call-CallModule");
	
	export default {
		components: {
			indexcom,
			infoself,
			orderself,
            websip,
			me
		},
		data() {
			return {
                xTask:0,
                yTask:0,
                
                xInfo:0,
                yInfo:0,
                
                xPhone:0,
                yPhone:0,
                
				message: '0',
				openId: '',
				access_token: '',
				tip: "我是提示",
				duration: 1,
				
				callCounts:0,
				orderCounts:0,
				
				status: 'more',
				contentText: {
					contentdown: '上拉加载更多',
					contentrefresh: '加载中',
					contentnomore: '没有更多'
				},
				callphone:0,
				
				sim1Number:'',
				sim2Number:'',
				phoneNumber: '',
				callLog:'',
				autoFlag: -1,
				autoFlagText: '未检测',
				
				isShowOpenVoice:false,
				isShowOpenFile:false,
				
				
				start_time:'', //通话开始时间
				end_time:'', //通话结束时间
				currentPhoneNumber:'',//当前通话号码 
				phonetype:'',
				taskForm:{},

				time:"",
				taskVoiceTime:null, //任务录音定时器
				
				taskTime:0,
                base_url:'', //服务器地址


                rootStyle:{
                    '--page-overflow':'auto',
                },
				
				callingTime:'',
                callingTimer:null,
                callTimeCount:0,
				
				isCallStatus:"",//通话状态，空：通话结束，call通话中
			};
		},
		computed: {
			...mapGetters(["userInfo","appUpdate","callCount","callTaskTimer","taskType","callTaskCountTimer","voiceServiceList","voiceList","sipPhone","isShowWebSip","callStatus","callingData","currentCallType"]),
			...mapState({
				PageCur: state => state.tabbar.PageCur,
				taskType: state => state.task.taskType,
				callCount: state => state.task.callCount,
				callTaskCountTimer:state=>state.task.callTaskCountTimer,
				callTaskTimer:state=>state.task.callTaskTimer,
				callType: state => state.task.callType,
				voiceList: state => state.task.voiceList,
                sipPhone:state=>state.task.sipPhone,
                isShowWebSip:state=>state.task.isShowWebSip,
                callStatus:state=>state.task.callStatus,
				callingData:state=>state.task.callingData,
				currentCallType:state=>state.task.currentCallType
			})
		},
		
		onLoad(option) {
			that = this;
			
			console.log("tabbar onload",option);
            
            const systemInfo = uni.getSystemInfoSync();
            this.xTask = systemInfo.screenWidth - 260;
            this.yTask = systemInfo.screenHeight - 140;
            
            this.xInfo = systemInfo.screenWidth - 70;
            this.yInfo = systemInfo.screenHeight - 260;
            
            this.xPhone = systemInfo.screenWidth - 70;
            this.yPhone = systemInfo.screenHeight - 190;
			
			//判断是否从任务外呼功能来
			that.callphone = option.type;
			
			//默认设置为进来显示首页
			// that.$store.dispatch("setPageCur","index");
		
			//开始SQLITE定时数据处理任务
			if(that.$globalData.sqliteTimer == null){
				console.log("tabbar onload sqlitetimer");
			    that.$globalData.sqliteTimer = setInterval(()=>{
			        that.handleSqliteList();
			    },3000);
			}
			
			//开始SQLITE定时数据处理录音
			if(that.$globalData.sqliteRecordTimer == null){
				console.log("tabbar onload sqliteRecordTimer");
			    that.$globalData.sqliteRecordTimer = setInterval(()=>{
			        that.handleSqliteRecordList();
			    },5000);
			}
		},
		
		onShow(option) {
			console.log("tabbar onshow option",this.$globalData.taskTimer,callModule);
            
            //注册通话监听
            setTimeout(()=>{
            	//启动通话监听				
            	that.handleRegisterListener();
            },1500);
            
            setTimeout(()=>{
            	//检测是否开启自动通话录音  和  获取所有文件权限
            	that.handleCheckPermission();
            },1000)
            
            //获取服务器地址
            let baseApiUrl = uni.getStorageSync("baseApiUrl");
            this.base_url = 'http://' + baseApiUrl + '/';
			
			console.log("tabbar onshow base_url",baseApiUrl,this.base_url);
			
			this.callCounts = this.callCount;
			
			this.$store.dispatch("setPageCur",this.PageCur);

			//获取一次提醒数量
			this.handleGetOrderRemindCount();
            
            // if(this.$globalData.threadTimer == null){
            //     this.$globalData.threadTimer = setInterval(()=>{
            //         this.handleTaskVoiceList();
            //     },3000);
            // }
			
		
		},
		
		onHide() {
			console.log("tabbar onhide",this.callTask,this.$globalData.taskTimer);
		
		},
        
        // onPageScroll(e){
        //     console.log("tabbar onpagescroll ",e);
            
        //     this.throttle(this.calculateElementPositions, 200)();
        // },
		
		//下拉刷新
		onPullDownRefresh (){
			console.log("tabbar onPullDownRefresh aaaaaaaaa");
            
            if(that.PageCur == 'index'){
            	that.$refs['index'].handleLoadMore('start');
            }else if(that.PageCur == 'info'){
            	that.$refs['info_self'].handleLoadMore('start');
            }else if(that.PageCur == 'order'){
            	that.$refs['order_self'].handleLoadMore('start');
            }else if(that.PageCur == 'me'){
                that.$refs['me'].getSeatData();
                that.$refs['me'].handleCbPhoneNumberInfo();
            }else{
                uni.stopPullDownRefresh();
            }
		},
		
		//上拉加载
		onReachBottom() {
			
			console.log("dddddd");
			
			if(that.PageCur == 'index'){
				that.$refs['index'].handleLoadMore('end');
			}else if(that.PageCur == 'info'){
				that.$refs['info_self'].handleLoadMore('end');
			}else if(that.PageCur == 'order'){
				that.$refs['order_self'].handleLoadMore('end');
			}
		},
		
		created() {
			console.log("tabbar created");
			
			that = this;

			uni.$on("handleGetCall",that.handleGetCall);
            
            uni.$on("getLoadMoreState",that.handleLoadMoreState);
            
            uni.$on("changePageStyle",that.changePageStyle);
			
			//判断是否是接收自动外呼数据
			if((this.taskType == undefined || this.taskType == '' || this.taskType == 0) && this.$globalData.taskTimer == null) {
				this.$globalData.taskTimer = setInterval(()=>{
					this.$globalData.taskTimerCount++;
					console.log("tabbar 定时任务获取"+ this.$globalData.taskTimerCount);
                    
                    this.$console.info("tabbar 定时任务获取"+ this.$globalData.taskTimerCount);
					
					this.handleGetCall();
				},2000);
			}
		},

        watch:{
            currentCallType(newVal,oldVal){
                console.log("tabbar currentcalltype",newVal,oldVal);
                if(newVal == 'sip'){
                    that.handleCallTime(1);
                }else{
                    that.handleCallTime(0);
                }
            },
            
            callingData: {
                handler(newVal, oldVal) {
                    console.log('数组变化 (深度监听) callingData', newVal,oldVal);
                    // 注意：oldVal 会与 newVal 相同（引用问题）
                    
                    if(newVal.state == 'callout'){
                        that.callTimeCount = -1;
                    }
                },
                deep: true, // 关键点：启用深度监听
            }
        },
        
		methods: {
			handleSqliteUpdate(){
				let open = DB.isOpen();
				
				if (open) {
					//测试先修改状态为未上传录音
					// let call_data = DB.updateTableData("call_cdr","status=0,cdr_id=''","cdr_id","32962").then();
                    
                    DB.selectTableDataOrder('call_cdr','ctime ASC',1,0,"sec = 0 and (audio_path == '' || audio_path == 'null')").then((res) => {
						console.log("aaaaaaaaaaaaaaaaaa",res);
					}).catch((error) => {
                        console.log('查询失败', error);
                    });
					
					DB.selectTableDataOrder('call_cdr','ctime ASC',1,0,"sec = 0 and (audio_path == '')").then((res) => {
						console.log("bbbbbbbbbbbbbbbbbbb",res);
					}).catch((error) => {
					    console.log('查询失败', error);
					});
					
					DB.selectTableDataOrder('call_cdr','ctime ASC',1,0,"sec = 0 and (audio_path == null)").then((res) => {
						console.log("ccccccccccccccc",res);
					}).catch((error) => {
					    console.log('查询失败', error);
					});
					
					DB.selectTableDataOrder('call_cdr','ctime ASC',1,0,"sec = 0 and (audio_path == 'null')").then((res) => {
						console.log("dddddddddddddd",res);
					}).catch((error) => {
					    console.log('查询失败', error);
					});
					
					// DB.findTableData("call_cdr","1=1").then((res)=>{
					// 	console.log("aaaaaaaaaaaaaaaaaa",res);
					// });
					// console.log("aaaaaaaaaaaaaaaaaa",call_data);
				}
				
			},
			
			//定时处理SQLITE数据库中的话单数据
			async handleSqliteList(){
				console.log("SQLITE定时器");
				
				let _this = this;
				
				//获取需要处理的数据
				let open = DB.isOpen();
				
				//先停止定时SQLITE任务
				clearInterval(_this.$globalData.sqliteTimer);
				_this.$globalData.sqliteTimer = null;
				
				if (open) {
					//测试先修改状态为未上传录音
					//DB.updateTableData("call_cdr","status=0","cdr_id","23334").then();
					
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					const call_list = await DB.selectTableDataOrder('call_cdr','ctime ASC',1,0,"cdr_id = ''").then((res) => res).catch((error) => {
					    console.log('查询失败', error);
					});
                    
                    console.log("SQLITE 定时任务获取数据",call_list);
					
					if(call_list.length){
						
						let call_data = call_list[0];
                        
                        console.log("!!!!!!!!!!!!!!",call_data);
						
                        //上传话单接口错误，重新调接口上传话单，并查询录音
                        if(call_data.cdr_id == "" || call_data.cdr_id == 'null'){
                            //重新上传话单
                            let call_params = {
                                "seat":call_data.seat,
                                "unum":call_data.num,
                                "stime":call_data.stime,
                                "etime":call_data.etime,
                                "ctime":call_data.stime,
                                "status":call_data.cdr_status,
                                "sec":call_data.sec,
                                "seatsec":call_data.sec,
                                "pid":call_data.pid,
                                "tid":call_data.tid,
                                "cid":call_data.cid
                            };
                            
                            console.log("SQLITE话单处理，添加话单:",call_data,call_params);
                            _this.$console.info("SQLITE话单处理，添加话单:",call_data,call_params);
                            
                            addCallOutDataNoVoicePro(call_params).then(res_add=>{
                                console.info("SQLITE话单处理，添加话单成功，",call_params,res_add);
                                _this.$console.info("SQLITE话单处理，添加话单成功，",call_params,res_add);
                                
                                //更新SQLITE数据表
                                DB.updateTableData("call_cdr","cdr_id="+res_add.data.data,"id",call_data.id);
								
								console.info("SQLITE话单处理，添加话单成功，更新到通话列表",call_params,res_add);
								_this.$console.info("SQLITE话单处理，添加话单成功，更新到通话列表",call_params,res_add);
								
								call_data.cdr_id = res_add.data.data;
								
								//更新到通话列表
								call_params.record = "";
								call_params.id = res_add.data.data;
								uni.$emit("appendCallList",call_params);
                                
                            }).catch(error_add=>{
                                console.info("SQLITE话单处理，添加话单失败，",call_params,error_add);
                                _this.$console.info("SQLITE话单处理，添加话单失败，",call_params,error_add);
                                
                                //更新当前SQLITE  的ctime时间
                                let current_time = getTime();
                                
                                DB.updateTableData("call_cdr","ctime='"+current_time+"'","id",call_data.id);
                                
                            });
							
							
							if(_this.$globalData.sqliteTimer == null){
								console.info("SQLITE话单处理，重新启动定时任务，",_this.$globalData.sqliteTimer);
								_this.$console.info("SQLITE话单处理，重新启动定时任务，",_this.$globalData.sqliteTimer);
								
								_this.$globalData.sqliteTimer = setInterval(()=>{
									_this.handleSqliteList();
								},3000);
							}
                        }else{
							if(_this.$globalData.sqliteTimer == null){
								console.info("SQLITE话单处理，重新启动定时任务，",_this.$globalData.sqliteTimer);
								_this.$console.info("SQLITE话单处理，重新启动定时任务，",_this.$globalData.sqliteTimer);
								
								_this.$globalData.sqliteTimer = setInterval(()=>{
									_this.handleSqliteList();
								},3000);
							}
						}
                        
					}else{
						if(_this.$globalData.sqliteTimer == null){
							console.info("SQLITE话单处理，重新启动定时任务，",_this.$globalData.sqliteTimer);
							_this.$console.info("SQLITE话单处理，重新启动定时任务，",_this.$globalData.sqliteTimer);
							
							_this.$globalData.sqliteTimer = setInterval(()=>{
								_this.handleSqliteList();
							},3000);
						}
					}
					
				}
			},
			
			//定时处理SQLITE数据库中的数据
			async handleSqliteRecordList(){
				console.log("SQLITE定时器");
				
				let _this = this;
				
				//获取需要处理的数据
				let open = DB.isOpen();
				
				//先停止定时SQLITE任务
				clearInterval(_this.$globalData.sqliteRecordTimer);
				_this.$globalData.sqliteRecordTimer = null;
				
				if (open) {
					//测试先修改状态为未上传录音
					//DB.updateTableData("call_cdr","status=0","cdr_id","23334").then();
					
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					const call_list = await DB.selectTableDataOrder('call_cdr','ctime ASC',1,0,"status = '0' and cdr_id != ''").then((res) => res).catch((error) => {
					    console.log('查询失败', error);
					});
			        
			        console.log("SQLITE录音 定时任务获取数据",call_list);
					
					if(call_list.length){
						
						let call_data = call_list[0];
			            
			            console.log("!!!!!!!!!!!!!!",call_data);
						
						//启动子线程任务
						console.log("SQLITE录音处理:");
						_this.$console.info("SQLITE录音处理:");
						
			            
			            let one_file_name = "";
			                    
			            //读取录音，结束时间为当前时间
			            let end_time = new Date().getTime();
			            let start_time = new Date(call_data.stime).getTime();
			            console.log("getroecorderfiles ",start_time,end_time);
						
						callModule.getRecorderFiles({
							//录音时间段
							times: [start_time, end_time]
						}, res_record => {
			                console.log("res_record",res_record);
			                        
							if(res_record.code == 0 && res_record.data.list.length > 0){
								//可能会获取到多条，匹配一下号码
								if(res_record.data.list.length == 1){
									one_file_name = res_record.data.list[0];
								}else{
									let record_files = res_record.data.files;
									for(let i=0;i<record_files.length;i++){
										let record_item_data = record_files[i].path.split("/");
										let record_number = record_item_data[record_item_data.length - 1].replace(/[^0-9]/g, ''); //过滤掉录音名称中其它字符，只保留数字  
										
										//判断录音的开始时间大于通话开始时间
										let cdr_stime = new Date(call_data.stime).getTime();
										if(record_number.indexOf(record_files[i].num) > -1 && record_files[i].time >= cdr_stime){
											one_file_name = record_files[i].path;
											
											break; //退出整个循环
										}
									}
								}
			                            
			                    if(one_file_name){
			                                
									//上传录音
									//let reader = new plus.io.FileReader();
									let file_array = one_file_name.split(".");
									let file_array_data = one_file_name.split("/");
																		
									// 在这里可以执行文件夹创建成功后的操作
									let full_path = uni.getStorageSync("record_files");
									callModule.copyFile({
										fromFilename: one_file_name,
										toFilename: full_path + file_array_data[file_array_data.length - 1]
									}, res_copyfile => {                                                      
										one_file_name = full_path + file_array_data[file_array_data.length - 1];
			                                                                                  
										console.log('录音处理--监听结果中有通话录音,当前时间， 拷贝录音文件到缓存目录:', call_data.num,res_copyfile,one_file_name);
										_this.$console.info("录音处理--监听结果中有通话录音,当前时间， 拷贝录音文件到缓存目录",call_data.num,res_copyfile,one_file_name);
										
										uni.uploadFile({
											url: request.baseUrl + 'api/Appdownload/uploadVoice',
											filePath: one_file_name,
											name: "file",
											header:{
												'content-type' : 'multipart/form-data'
											},
											formData: {
												seat: uni.getStorageSync("userInfo").seat,
												num:call_data.num,
												filePath: one_file_name,
												id:call_data.cdr_id
											},
											success: (res_upload) => {
												// console.log("文件上传成功")
												let current_upload_data = JSON.parse(res_upload.data);
												
												console.log('录音处理--监听结果中有通话录音,当前时间， 上传录音:', call_data.num,one_file_name);
												_this.$console.info('录音处理--监听结果中有通话录音,当前时间， 上传录音:', call_data.num,one_file_name);
												
												
												console.log("uni.uploadFile res",current_upload_data);
												
												//更新通话列表
												//接口,修改通话录音
												let update_voice_params = {
												    'id':call_data.cdr_id,
												    'voice_url':current_upload_data.data.path
												}
												uni.$emit("updateCallList",update_voice_params);
												
												if (open) {
													DB.updateTableData('call_cdr', "audio_path = '"+one_file_name+"',status='1'", "id",call_data.id).then((res_status) => {
														_this.$console.info("SQLITE录音处理--录音子线程处理, 修改通话记录数据 参数 SQLITE:",call_data.num,res_upload.data,res_status);
														console.log("SQLITE录音处理--录音子线程处理, 修改通话记录数据 参数 SQLITE:",call_data.num,res_upload.data,res_status);
														
													}).catch((error_status) => {
														_this.$console.info("SQLITE录音处理--录音子线程处理, 修改通话记录数据 参数 SQLITE 失败:",error_status);
														console.log("SQLITE录音处理--录音子线程处理, 修改通话记录数据 参数 SQLITE 失败:",error_status);
													})
												}
												
												//删除文件
												setTimeout(()=>{
													callModule.deleteFile({
														filePath: one_file_name
													}, res_deletefile => {
														console.info("录音处理--没有录音文件，第三方接口获取录音。当前时间，转换录音文件后删除文件",call_data.num,one_file_name,res_deletefile);
														_this.$console.info("录音处理--没有录音文件，第三方接口获取录音。当前时间，转换录音文件后删除文件",call_data.num,one_file_name,res_deletefile);
													})
												},1000);
												
												//开启定时器
												if(_this.$globalData.sqliteRecordTimer == null){
													_this.$globalData.sqliteRecordTimer = setInterval(()=>{
														_this.handleSqliteRecordList();
													},5000);
												}
												
											},
											fail(err) {
												console.log("文件上传失败")
												console.log("uni.uploadFile err",err);
												
												_this.$console.info("SQLITE录音处理--文件上传失败:",err);
												
												//开启定时器
												if(_this.$globalData.sqliteRecordTimer == null){
													_this.$globalData.sqliteRecordTimer = setInterval(()=>{
														_this.handleSqliteRecordList();
													},5000);
												}
											},
											complete(e) {
												// uni.hideToast();
												console.log("complete",e);
												
												_this.$console.info("SQLITE录音处理--文件上传失败 complete:",e);
												
												//开启定时器
												if(_this.$globalData.sqliteRecordTimer == null){
													_this.$globalData.sqliteRecordTimer = setInterval(()=>{
														_this.handleSqliteRecordList();
													},5000);
												}
											}
										})

									})
			                                
			                    }else{
									//更新SQLITE时间
									DB.updateTableData("call_cdr","ctime = '"+getTime()+"'","id",call_data.id).then(ress=>{
										console.log(ress);
									});
			                                
									setTimeout(()=>{
										console.log("SQLITE录音处理--子线程处理完，重新开启线程定时器并关闭线程 ",call_data.num);
										_this.$console.info("SQLITE录音处理--子线程处理完，重新开启线程定时器并关闭线程 ",call_data.num);
										
										//开启定时器
										if(_this.$globalData.sqliteRecordTimer == null){
											_this.$globalData.sqliteRecordTimer = setInterval(()=>{
												_this.handleSqliteRecordList();
											},5000);
										}
											
										
									},1000);
								}
			                }else{
			                    //更新SQLITE时间
			                    DB.updateTableData("call_cdr","ctime = '"+getTime()+"'","id",call_data.id).then(ress=>{
			                        console.log(ress);
			                    });
			                            
								setTimeout(()=>{
									console.log("SQLITE录音处理--子线程处理完，重新开启线程定时器并关闭线程 ",call_data.num);
									_this.$console.info("SQLITE录音处理--子线程处理完，重新开启线程定时器并关闭线程 ",call_data.num);
									
									//开启定时器
									if(_this.$globalData.sqliteRecordTimer == null){
										_this.$globalData.sqliteRecordTimer = setInterval(()=>{
											_this.handleSqliteRecordList();
										},5000);
									}
										
									
								},1000);
							}
			            })
			                    
			        
			        }else{

						console.log("SQLITE录音处理--没有需要获取的录音，重新开启线程定时器并关闭线程 ");
						_this.$console.info("SQLITE录音处理--没有需要获取的录音，重新开启线程定时器并关闭线程 ");
				
						
						//开启定时器
						if(_this.$globalData.sqliteRecordTimer == null){
							_this.$globalData.sqliteRecordTimer = setInterval(()=>{
								_this.handleSqliteRecordList();
							},5000);
						}
					}
					
				}
			},
			
			
			//呼叫计时器
			handleCallTime(type){
				if(type == 1 && that.callingTimer == null){
					that.callingTimer = setInterval(() => {
						that.callTimeCount++;
		
						that.callingTime = getHms(that.callTimeCount);
					}, 1000);
				}else{
					//清除计时器
					clearInterval(that.callingTimer);
					that.callingTimer = null;
		
					that.callTimeCount = -1;
					that.callingTime = "";
				}
			},
				
			//挂断通话
			handleEndCall(){
			    callModule.endCall(res => {
			        console.log("endCall",res);
			        console.log("currentCallType",that.currentCallType);
			      
			        that.$store.dispatch("setCallStatus",0);
					that.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
			      
			        if(that.currentCallType == 'sip'){
			            //通知SIP  挂断通话
			            // websip.methods.handleSendMessage('hangup',{});
			          
			            that.$store.dispatch("setWebsipCallStatus","hangup");
						that.$store.dispatch("setCurrentCallType","");
			        }
			    });
			},

            //修改overflow属性
            changePageStyle(val){
                console.log("changepagestyle val",val);
                
                this.rootStyle = {
                    '--page-overflow': 'hidden '
                  }
            },
            
            //测试
			handleGetRecordList(){
				// 请求权限（示例）
				// 获取 SipManager 实例
				const SipManager = plus.android.importClass('android.net.sip.SipManager');
				const context = plus.android.runtimeMainActivity();
				const sipManager = SipManager.newInstance(context);
                
                console.log("handlegetrecordlist sipManager",sipManager);
				
				// 检查 SIP 是否支持
				if (!sipManager.isSipSupported()) {
				  uni.showToast({ title: '设备不支持 SIP', icon: 'none' });
				  
				}
			},
			
            //显示拨号盘
            onHandleOpenCallPhone(){
                let navigate_url = "/pages/index/callPhone";
                
                console.log("currentData",navigate_url);
                
                navigate_url += "?phone=&type=1";
                
                uni.navigateTo({
                	url: navigate_url
                })
            },
                
            //呼叫下一个
            handleCallNext(){
                if(this.isCallStatus == ""){
                    // this.isCallStatus = "call";
                    infoself.methods.handleCallNext();
                }else{
                    console.log("handlecallnext ",this.isCallStatus);
                }
            },
            
			//开启注册监听通话
			handleRegisterListener(){
				let _this = this;
                
				callModule.registerListener(res => {
					let call_data = res;
					let global_calldata = _this.$globalData.callData;
                    // let global_userphonenumber = _this.$globalData.userPhoneNumber;
					
					let open = DB.isOpen();
                    
                    console.log("通话监听注册 registerListener",res,global_calldata);
                    _this.$console.info("通话监听注册 registerListener",res,global_calldata);
					
					//TODO  判断是否在通话中或通话结束，先设置成通话中
					if(call_data.data.status != undefined && (call_data.data.status != 1 && call_data.data.status != 6)){
					    _this.isCallStatus = "call";
					}
					
                    //处理通话状态是  3.电话挂断  5.去电对方拒接或未接听，6.通话中时来电占线  状态为呼出isIncoming
					if((call_data.data.status == 3 || call_data.data.status == 5) && call_data.data.phoneNumber != '' && call_data.data.isIncoming == false){
						
						_this.isCallStatus = "";
                        
                        //设置通话状态为结束
                        _this.$store.dispatch("setCallStatus",0);
						_this.$store.dispatch("setCallingData",{id:"",phone:"",type:""});

                        //匹配缓存中的当前呼叫数据
                        let add_data = {};
                        let global_data = [];
						
						for(let i = 0; i < _this.$globalData.callData.length;i++){
							if(_this.$globalData.callData[i].callee == call_data.data.phoneNumber){
								add_data = _this.$globalData.callData[i];
								
								_this.$globalData.callData.splice(i,1);
							}
						}
                        
                        // _this.$globalData.callData = global_data;
                        
                        console.log('-------通话监听，通话结束,获取缓存数据，',call_data.data.phoneNumber,add_data,_this.$globalData.callData);
                        _this.$console.info('通话监听，通话结束,获取缓存数据，',call_data.data.phoneNumber,add_data,_this.$globalData.callData);

                        //记录结束时间
                        let end_time = getTime();
                        
                        let status = '0';
                        let cdr_status = 2;
                        let sec = 0;
                        
                        //状态，时长为0，没有录音，status=1
                        status = call_data.data.duration == undefined ? '1' : (call_data.data.duration*1 <= 0 ? '1':'0');
                            
                        //通话状态
                        cdr_status = ((call_data.data.status == 3 || call_data.data.status == 5 || call_data.data.status == 6) && call_data.data.duration*1 > 0) ? 2 : 3;
                            
                        //时长 插件返回的有可能有问题，
                        sec = call_data.data.duration == undefined ? 0 : (call_data.data.duration*1/1000).toFixed(0);
                        
                        let call_params = {
                            "seat":add_data.seat,
                            "cid":add_data.company_id,
                            "pid":add_data.pid,
                            "tid":add_data.tid,
                            "stime":add_data.start_time,
                            "unum":add_data.callee,
                            "etime":end_time,
                            "status":cdr_status,
                            "sec":sec,
                            "seatsec":sec
                        };
                            
                        console.log("通话结束,保存通话记录错误，保存数据到SQLITE",call_data.data.phoneNumber);
                        _this.$console.info("通话结束,保存通话记录错误，保存数据到SQLITE",call_data.data.phoneNumber);
                            
                        //添加到SQLITE中								
                        if(open){
                            //let ctime = getTime(); //当前时间
                            let sql = `'${call_params.seat}','${call_params.unum}','${call_params.stime}','${end_time}','${call_data.data.uuid}','${call_params.cid}','${call_params.pid}','${call_params.tid}','${status}','${cdr_status}','${sec}','${end_time}',''`;
                            let condition = "'seat','num','stime','etime','type','cid','pid','tid','status','cdr_status','sec','ctime','cdr_id'";
                            // 新增 DB.insertTableData(表名, 对应表头列的数据)
                            DB.insertTableData('call_cdr', sql, condition).then((res_err_insert) => {
                                console.log('通话结束,保存通话记录错误，保存数据到SQLITE 数据添加成功 ',res_err_insert,sql,condition);
                                _this.$console.info('通话结束,保存通话记录错误，保存数据到SQLITE 数据添加成功 ',res_err_insert);
                            }).catch((res_err_err) => {
                                _this.$console.info('通话结束,保存通话记录错误，保存数据到SQLITE 失败', res_err_err);
                            })
                        }
						
                        console.log("通话结束,判断是否需要开启自动接收外呼",_this.taskType,_this.$globalData.taskTimer);
                        _this.$console.info("通话结束,判断是否需要开启自动接收外呼",_this.taskType,_this.$globalData.taskTimer);
                        
						//开启任务定时器
						if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
							_this.$globalData.taskTimer = setInterval(()=>{
								_this.handleGetCall();
							},2000);
						}
                        
                        //如果是任务中的自动外呼，判断是否为自动外呼开启状态
                        if(_this.$globalData.autoCallStatus == 1){
                            setTimeout(()=>{
                                InfoSelf.methods.handleAutoCallNext();
                            },3000);
                        }
                    }else if(call_data.data.status == 1 || call_data.data.status == 6){
                        //来电
                        _this.$store.dispatch("setCallStatus",1);
                    }else if(call_data.data.status != 2){
                        //设置通话状态为结束
                        _this.$store.dispatch("setCallStatus",0);
						_this.$store.dispatch("setCallingData",{id:'',phone:'',type:''});
                    }else if(call_data.data.status == 2){
                        //通话状态为通话中 判断SQLITE中是否存在  UUID   ,不存在添加一条, 先把话单添加到平台
                        				
						console.log('通话监听，通话中,',call_data);
						_this.$console.info('通话监听，通话中,',call_data);
                    }
				});
				
				callModule.startForeground({
				  //前台通知服务标题
				  title: "",
				  //前台通知服务内容
				  content: "CM通话监听程序正在运行中",
				  //icon图标名称，不需要加后缀名，需放置到【nativeplugins】>【leven-call】> 【android】> 【res】> 【mipmap】>图片名称
				  icon: "icon"
				}, res => {
				  //this.writeLog(JSON.stringify(res))
				  console.log("前台通知服务标题 startForeground",res);
				  _this.$console.info("前台通知服务标题 startForeground",res);
				});
			},
			
			//检测是否开启自动通话录音及获取所有的文件权限
			handleCheckPermission(){
				let _this = this;
				console.log("检测通话录音权限");
				console.log(callModule);
                
                setTimeout(()=>{
                    //检测通话录音权限
                    callModule.checkCallAutoRecorder(res => {
                        console.log("检测通话录音权限 结果",res);
                        
                        _this.$console.info("检测通话录音权限 结果",res);
                        
                        if(!res.data.isOpen){
                            console.log("未开启自动通话录音");
                            
                            _this.$console.info("未开启自动通话录音");
                            //提示，没有开启自动通话录音
                            _this.isShowOpenVoice = true;
                        }else{
                            
                        }
                    });
                    
                    //检测获取所有文件权限
                    console.log("检测获取所有文件权限");
                    _this.$console.info("检测获取所有文件权限");
                    callModule.checkAllFilesPermission(res_file => {
                        console.log("检测获取所有文件权限 结果",res_file);
                        _this.$console.info("检测获取所有文件权限 结果",res_file);
                        if(!res_file.data.status){
                            console.log("检测获取所有文件权限 未开启");
                            _this.$console.info("检测获取所有文件权限 未开启");
                            _this.isShowOpenFile = true;
                        }
                    });
                },2500)
            },
			
			//开启自动通话录音
			confirmOpenVoice() {
				callModule.toCallAutoRecorderPage(res => {
					console.log("开启通话自动录音",res);
					
					this.$console.info("开启通话自动录音",res);
				});
			},
			
			//开启所有文件访问权限页面
			confirmOpenFile(){
				callModule.toAllFilesPermissionPage(res => {
					console.log("所有文件访问权限页面",res);
					this.$console.info("所有文件访问权限页面",res);
				});
			},
			
			NavChange: function(e) {
				console.log("navchange userinfo",this.PageCur,e);
				
				if(this.PageCur != e.currentTarget.dataset.cur){
					this.$store.dispatch("setPageCur",e.currentTarget.dataset.cur);
					
					if(e.currentTarget.dataset.cur === 'index'){
						this.$nextTick(()=>{
							console.log("tabbar refs") // 输出实例
							// console.table(this.$refs['index']);
							
							this.$refs['index'].handleInitData(0);
						});
					}
					
					if(e.currentTarget.dataset.cur == 'info'){
                        // const systemInfo = uni.getSystemInfoSync();
                        
                        // this.xInfo = systemInfo.screenWidth - 70;
                        // this.yInfo = systemInfo.screenHeight - 190;
						
						this.$refs['info_self'].handleInitData(0);
					}
					
					if(e.currentTarget.dataset.cur == 'order'){
						
						this.$refs['order_self'].handleInitData(0);
					}
                    
                    if(e.currentTarget.dataset.cur == 'websip'){
                        this.$store.dispatch("setIsShowWebSip",0);
                    }else{
                        this.$store.dispatch("setIsShowWebSip",1);
                    }
                    
                    console.log("navchange userinfo aaaaa",this.PageCur);
				}
				
				if(this.userInfo.order_url != null && this.userInfo.order_url != ''){
					//每次点击 订单获取提醒数量
					this.handleGetOrderRemindCount();
				}
			},
			
			//每次点击 订单获取提醒数量
			handleGetOrderRemindCount(){
				//if(this.PageCur == 'order' && userinfo.order_url == null){
					// getOrderRemindCount({seat_id:this.userInfo.id,company_id:this.userInfo.company_id}).then(res=>{
					// 	this.orderCounts = res.data.data;
					// });
				//}
			},
            
			//定时任务
			handleGetCall(){
			    let _this = this;
				//判断callTask是否为空
				console.log("定时任务开始 ----------------");
                _this.$console.info("定时任务开始 ----------------");

                // if(_this.taskType == 0){
				// 通话监听状态返回后才可以获取APP数据
				if(_this.taskType == 0 && _this.isCallStatus == ""){
                    
                    //先清除任务
                    clearInterval(_this.$globalData.taskTimer);
                    _this.$globalData.taskTimer = null;
                    
                    let params = {
                        "seat":uni.getStorageSync("userInfo").seat
                    };
                    
                    //console.log("定时任务，当前任务数：",this.callCounts);
                    
                    //判断是否需要获取数量
                    if(_this.callCounts > 0){
                        params.isCount = 1;
                    }else{
                        params.isCount = 0;
                    }
                    
                    try{
                        getCallTaskBlack(params).then((res)=>{

                            //记录日志
                            console.info("定时任务返回数据 res",res);
                            _this.$console.info("定时任务返回数据 res",res);
                            
                            if(res.data.code == 200){
                                let current_data = res.data.data;
                                
                                //减少数量
                                if(_this.callCounts > 1){
                                    _this.callCounts--;
                                    _this.$store.dispatch("setCallCount",_this.callCounts);
                                    //console.log("定时任务，任务数大于1，减1后的数：",this.callCounts);
                                }else{
                                    _this.callCounts = res.data.count;
                                    _this.$store.dispatch("setCallCount",_this.callCounts);
                                    //console.log("定时任务，任务数小于1 ，使用返回任务数，减少任务数：",(this.callCounts)*1-1);
                                }
                                
                                if(current_data != null && current_data.num){
                                    //外呼
                                    _this.$console.info("定时任务返回数据 开始外呼",current_data);
									if(current_data.is_call == 1){
										callModule.checkCallAutoRecorder(res_module => {
											console.log("检测通话录音权限 结果",res_module);
											
											_this.$console.info("检测通话录音权限 结果",res_module);
											
											if(!res_module.data.isOpen){
												console.log("未开启自动通话录音");
												
												_this.$console.info("未开启自动通话录音");
												
												//提示，没有开启自动通话录音
												_this.isShowOpenVoice = true;
												
											}else{
												_this.isShowOpenVoice = false;
												_this.handleCallPhone(current_data);
											}
										});
									}else{
										_this.handleCallPhone(current_data);
									}
									
                                    //_this.handleCallPhone(current_data);
                                }
                            }else{
                                //开启任务定时器
                                if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
                                    _this.$globalData.taskTimer = setInterval(()=>{
                                        _this.handleGetCall();
                                    },2000);
                                }
                            }
                        }).catch(err=>{
                            console.info("定时任务返回数据 err",err);
                            _this.$console.info("定时任务返回数据 err",err);
                            
                            //开启任务定时器
                            if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
                                _this.$globalData.taskTimer = setInterval(()=>{
                                    _this.handleGetCall();
                                },2000);
                            }
                        });
                    
                    }catch(err){
                        console.info("定时任务异常 err",err);
                        _this.$console.info("定时任务异常 err",err);
                        
                        //开启任务定时器
                        if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
                            _this.$globalData.taskTimer = setInterval(()=>{
                                _this.handleGetCall();
                            },2000);
                        }
                    }
                }
			},
			
			//呼起拨号盘
			handleCallPhone(data){
				let _this = this;
                
				_this.currentPhoneNumber = data.num;
				_this.taskForm = data;
				
				//调用接口
				let params = {
					'company_id':_this.userInfo.companyid,
					'caller':_this.userInfo.seat,
					'callee':data.num,
					'seat':_this.userInfo.seat,
					'pid':(data.pid == "" || data.pid == null || data.pid == undefined) ? _this.userInfo.pid : data.pid,
					'tid':data.tid,
					'type':3
				}
				
				console.log("infoself params",params);
                
                //先清除任务
                clearInterval(_this.$globalData.taskTimer);
                _this.$globalData.taskTimer = null;

				if(params.callee != '' && params.callee != null && params.callee != undefined){
                    //通话状态监听
                    params.start_time = getTime();
                    
					//记录日志
					console.info("APP外呼--开始外呼 参数",params);
					_this.$console.info("APP外呼--开始外呼 参数",params);
									
					//放入全局参数
					_this.$globalData.callData.push(params);
					
					//自动拨号
					plus.device.dial(params.callee,false);
					
					_this.$console.info("APP外呼--转到手机系统外呼 ",params);

				}else{
                    _this.$console.info("APP外呼--号码为空 参数",params);
                    
					//开启任务定时器
					if(_this.taskType == 0 && _this.$globalData.taskTimer == null){
						_this.$globalData.taskTimer = setInterval(()=>{
							_this.handleGetCall();
						},2000);
					}
				}

			},

			handleLoadMoreState(val){
                console.log("handleLoadMoreState val",val);
				that.status = val;
			},
	
		},

	}
</script>

<style lang="scss">
    // page{
    //     overflow:hidden !important;
    // }
    
	.color_main {
		color: #000000;
		font-weight: 900;
	}

	.box {
		// margin: 20upx 0;
	}

	.box view.cu-bar {
		// margin-top: 20upx;
	}

	.logo_btn {
		width: 38*2rpx;
		height: 38*2rpx;
		position: absolute;
		z-index: 100000000000000000000000000000;
		border-radius: 50%;
		top: -40rpx;
		left: 0rpx;
		right: 0;
		margin: auto;
		padding: 0;
	}

	.cu-bar.tabbar .action.add-action {
		padding-top: 56rpx !important;
	}
	
	.slot-content{
		width:90%;
		margin-left:5%;
		padding-top:20rpx;
		padding-bottom:20rpx;
		font-size:32rpx;
		line-height:50rpx;
		height:340rpx;
	}
	
	.slot-content text{
		width:100%;
		float:left;
		clear:both;
	}
	
	.task_panel{
		background-color:#3cb32a;
		border-radius: 40rpx;
		color:#fff;
		
		width:390rpx;
		height:100rpx;
		
		padding-top:15rpx;
		padding-left:25rpx;

		text-align: center;
		
		text-shadow: 5rpx 5rpx 5rpx #7a7a7a ;
		box-shadow: 15rpx 15rpx 18rpx #bfbfbf ;
	}
	
	.task_panel text{
		font-size:30rpx;
	}
    
    .call_next{
    	background-color:#075AFF;
    	border-radius: 60rpx;
    	color:#fff;
    	
    	width:120rpx;
    	height:120rpx;
    	
    	padding-top:25rpx;
    
    	text-align: center;
        line-height:35rpx;
    	
    	text-shadow: 5rpx 5rpx 5rpx #7a7a7a ;
    	box-shadow: 15rpx 15rpx 18rpx #bfbfbf ;
    }
	
	.call_next_nocall{
	    background-color:#cfd0cf;
	    border-radius: 60rpx;
	    color:#474747;
	    
	    width:120rpx;
	    height:120rpx;
	    
	    padding-top:25rpx;
	        
	    text-align: center;
	    line-height:35rpx;
	    
	    text-shadow: 5rpx 5rpx 5rpx #eaeaea ;
	    box-shadow: 15rpx 15rpx 18rpx #bfbfbf ;
	}
    
    .number_panel{
    	background-color:#075AFF;
    	border-radius: 60rpx;
    	color:#fff;
    	
    	width:120rpx;
    	height:120rpx;
    	
    	padding-top:15rpx;
    	
    	text-align: center;
    	
    	text-shadow: 5rpx 5rpx 5rpx #7a7a7a ;
    	box-shadow: 15rpx 15rpx 18rpx #bfbfbf ;
    }
    
    .number_panel .iconfont{
    	font-size:60rpx;
    }
    
    .number_panel .txt{
    	display: block;
    	clear:both;
    	width: 100%;
    	font-size:25rpx;
    }
    
    movable-view {
    	display: flex;
    	align-items: center;
    	justify-content: center;
    	height: 120rpx;
    	width: 120rpx;
        
        position:fixed !important;
        
        // z-index: 100000000000 !important;
        
        pointer-events: auto;
    }
    
    movable-area {
    	height: 100vh;
    	width: 100%;
    	overflow: hidden;
        z-index:1000 !important;
        
        position:absolute;
        top:0px;
        
        pointer-events: none;
    }
</style>